# Simple implementation of some sorting algorithms.

N: 100 .     # array size

~array:256   # memory for the array
~ptr:0       # helper pointers
~ptr2:0

generateRandom:

  $array>ptr

  11 $:ptr           # 11 is random seed

  N -- @'
    $ptr
    5 * 3 + 16 %
    $>ptr
    $:ptr
    --
  .
  ^
.

printArray:
  $array>ptr

  N @'
    $ptr "A" + ->
    $>ptr
    --
  .
  ^
.

sortBubble:
  N -- @'
    $array>ptr            # get to array start

    $0 @'
      $ptr $>ptr $ptr     # load two consecutive

      > ?
        $ptr $<ptr $ptr   # load the two neighbours again
        ><                # swap them
        $:ptr $>ptr $:ptr # write them back
      .

      --
    .
    ^
    --
  .
  ^
.

sortInsert:
  $array>ptr

  N -- @'
    $>ptr

    $ptr>ptr2

    1 @
      $ptr2
      $<ptr2
      $ptr2

      $1 $1     # duplicate the pair

      < ?
        ><      # swap the values and write them back
        $:ptr2
        $>ptr2
        $:ptr2
        $<ptr2
      ;
        ^ ^     # otherwise just pop them
      .

      $ptr2=array
    .

    --
  .
.

#----------

generateRandom

0 "original array: " -->

printArray 10 ->

0 "bubble sort:    " -->
generateRandom
sortBubble
printArray 10 ->

0 "insertion sort: " -->
generateRandom
sortInsert
printArray 10 ->
